package test.thread ;

import java.util.concurrent.CountDownLatch ;

import test.thread.JudgeSleepReleaseLock.ThreadA ;
import test.thread.JudgeSleepReleaseLock.ThreadB ;

/**
 * @author 80002165 @date 2017年4月27日 下午3:51:06
 */
public class JudgeSuspendReleaseLock {
    static class ThreadA extends Thread {
        Object lock ;
        
        public ThreadA(Object lock) {
            super("线程A") ;
            this.lock = lock ;
        }
        
        @SuppressWarnings("deprecation")
        @Override
        public void run() {
            synchronized (this.lock) {
                int i = 1 ;
                for (; i < 20; i++) {
//                    System.out.println("我得到了lock锁" + i++) ;
                    i++ ;
                    if (i == 10) {
//                        System.out.println("好累，我要休息一下！暂停线程") ;
                        suspend() ;
                    }
                }
            }
        }
    }
    
    static class ThreadB extends Thread {
        Object lock ;
        CountDownLatch flag ;
        
        public ThreadB(Object lock, CountDownLatch flag) {
            super("线程B") ;
            this.lock = lock ;
            this.flag = flag ;
        }
        
        @Override
        public void run() {
            System.out.println("我是线程B，我是在等待，一个锁对象！") ;
            synchronized (this.lock) {
                System.out.println("千年等一会，噢噢噢噢，我等到了锁！") ;
            }
            System.out.println("我要走了，掰掰！") ;
            flag.countDown() ;
        }
    }
    
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException {
        System.out.println("呜呜呜，测试开始啦!") ;
        CountDownLatch flag = new CountDownLatch(1) ;
        Object lock = new Object() ;
        ThreadA a = new ThreadA(lock) ;
        ThreadB b = new ThreadB(lock, flag) ;
        
        a.start() ;
        
        // 确保A线程先获得锁对象
        Thread.sleep(500) ;
        
        b.start() ;
        flag.await();
        System.out.println(b.isAlive()) ;
        a.resume(); 
    }
}
